package com.imooc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.pojo.R;
import com.imooc.pojo.User;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;

@RestController
@RequestMapping("/redis")
public class RedisController {

	@Autowired
	private StringRedisTemplate strRedis;
	
	@Autowired
	private RedisOperator redis;
	
	@RequestMapping("/test")
	public R test(){
		strRedis.opsForValue().set("albin-cache", "hello hds");
		
		User user = new User();
		
		user.setAge(50);
		user.setBirthday(new Date());
		user.setDesc("this is a user");
		user.setName("andy Lau");
		user.setPassword("123456");
		
		strRedis.opsForValue().set("json:user", JsonUtils.objectToJson(user));
		
		User rUser = JsonUtils.jsonToPojo(strRedis.opsForValue().get("json:user"), User.class);
		
		return R.ok(rUser);
	}
	
	@RequestMapping("/list")
	public R list(){
		User user1 = new User();
		
		user1.setAge(50);
		user1.setBirthday(new Date());
		user1.setDesc("this is a user1");
		user1.setName("andy Lau1");
		user1.setPassword("123456");
		
		User user2 = new User();
		
		user2.setAge(50);
		user2.setBirthday(new Date());
		user2.setDesc("this is a user2");
		user2.setName("andy Lau2");
		user2.setPassword("123456");
		
		User user3 = new User();
		
		user3.setAge(50);
		user3.setBirthday(new Date());
		user3.setDesc("this is a user3");
		user3.setName("andy Lau3");
		user3.setPassword("123456");
		
		
		List<User> list = new ArrayList<>();
		list.add(user1);
		list.add(user2);
		list.add(user3);
		
		redis.set("json:info:userList", JsonUtils.objectToJson(list), 2000);
		String userListJson = redis.get("json:info:userList");
		List<User> userList = JsonUtils.jsonToList(userListJson, User.class);
		
		return R.ok(userList);
	}
	
}
